<template>
  <div class="account-page">
    <div class="page-header">
      <h1 class="page-title">账号管理</h1>
      <p class="page-description">管理系统中的账号信息</p>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon account-icon">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ accounts.length }}</div>
            <div class="stat-label">账号总数</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon wechat-icon">
            <el-icon><ChatDotRound /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ wechatAccounts }}</div>
            <div class="stat-label">微信账号</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon other-icon">
            <el-icon><Operation /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ otherAccounts }}</div>
            <div class="stat-label">其他账号</div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 账号列表 -->
    <el-card class="account-list-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon><Setting /></el-icon>
            <span>账号列表</span>
          </div>
          <div class="header-right">
            <el-button
              type="primary"
              :icon="Plus"
              @click="showAddDialog"
            >
              添加账号
            </el-button>
            <el-button
              type="info"
              :icon="Refresh"
              :loading="loading"
              @click="loadAccounts"
            >
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="filter-section">
        <div class="filter-row">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索账号名或别名"
            :prefix-icon="Search"
            style="width: 300px"
            @input="handleSearch"
          />
          <el-select
            v-model="filterType"
            placeholder="账号类型"
            style="width: 150px; margin-left: 12px"
            @change="handleSearch"
          >
            <el-option label="全部" value="" />
            <el-option label="微信" value="wechat" />
            <el-option label="小红书" value="xiaohongshu" />
            <el-option label="抖音" value="douyin" />
            <el-option label="快手" value="kuaishou" />
            <el-option label="WhatsApp" value="whatsapp" />
          </el-select>
        </div>
      </div>
      
      <!-- 账号表格 -->
      <el-table
        :data="filteredAccounts"
        style="width: 100%"
        :loading="loading"
        empty-text="暂无账号数据"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="account" label="账号" min-width="150">
          <template #default="{ row }">
            <div class="account-cell">
              <span class="account-name">{{ row.account }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="alias" label="别名" width="150">
          <template #default="{ row }">
            <span v-if="row.alias">{{ row.alias }}</span>
            <span v-else class="no-alias">-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="account_type" label="账号类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getAccountTypeColor(row.account_type)" size="small">
              {{ getAccountTypeLabel(row.account_type) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            <span>{{ formatTime(row.created_at) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              :icon="Edit"
              @click="editAccount(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="deleteAccount(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredAccounts.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑账号对话框 -->
    <el-dialog
      v-model="accountDialog.visible"
      :title="accountDialog.isEdit ? '编辑账号' : '添加账号'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="accountFormRef"
        :model="accountDialog.form"
        :rules="accountRules"
        label-width="80px"
      >
        <el-form-item label="账号" prop="account">
          <el-input
            v-model="accountDialog.form.account"
            placeholder="请输入账号"
            :disabled="accountDialog.isEdit"
          />
        </el-form-item>
        
        <el-form-item label="别名" prop="alias">
          <el-input
            v-model="accountDialog.form.alias"
            placeholder="请输入别名"
          />
        </el-form-item>
        
        <el-form-item label="账号类型" prop="account_type">
          <el-select
            v-model="accountDialog.form.account_type"
            placeholder="请选择账号类型"
            style="width: 100%"
          >
            <el-option label="微信" value="wechat" />
            <el-option label="小红书" value="xiaohongshu" />
            <el-option label="抖音" value="douyin" />
            <el-option label="快手" value="kuaishou" />
            <el-option label="WhatsApp" value="whatsapp" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="accountDialog.visible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="accountDialog.loading"
            @click="submitAccount"
          >
            {{ accountDialog.isEdit ? '更新' : '添加' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User,
  ChatDotRound,
  Operation,
  Setting,
  Plus,
  Refresh,
  Search,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { accountAPI } from '@/api'

// 响应式数据
const loading = ref(false)
const accounts = ref([])
const searchKeyword = ref('')
const filterType = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const selectedAccounts = ref([])

// 账号对话框
const accountDialog = reactive({
  visible: false,
  loading: false,
  isEdit: false,
  form: {
    account: '',
    alias: '',
    account_type: 'wechat'
  }
})

// 表单引用
const accountFormRef = ref(null)

// 表单验证规则
const accountRules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 1, max: 100, message: '账号长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  alias: [
    { required: true, message: '请输入别名', trigger: 'blur' },
    { min: 1, max: 100, message: '别名长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  account_type: [
    { required: true, message: '请选择账号类型', trigger: 'change' }
  ]
}

// 计算属性
const filteredAccounts = computed(() => {
  let result = accounts.value
  
  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(account => 
      account.account.toLowerCase().includes(keyword) ||
      (account.alias && account.alias.toLowerCase().includes(keyword))
    )
  }
  
  // 类型过滤
  if (filterType.value) {
    result = result.filter(account => account.account_type === filterType.value)
  }
  
  return result
})

const wechatAccounts = computed(() => {
  return accounts.value.filter(account => account.account_type === 'wechat').length
})

const otherAccounts = computed(() => {
  return accounts.value.filter(account => account.account_type !== 'wechat').length
})

// 方法
const loadAccounts = async () => {
  loading.value = true
  try {
    const response = await accountAPI.getAccounts()
    console.log('账号列表响应:', response)
    
    if (response.success && response.data) {
      // 处理后端返回的数据结构
      let accountsData = [];
      
      if (response.data.accounts && Array.isArray(response.data.accounts)) {
        // 标准结构：data.accounts数组
        accountsData = response.data.accounts;
      } else if (Array.isArray(response.data)) {
        // 兼容可能的直接返回数组的情况
        accountsData = response.data;
      } else {
        console.error('未知的账号数据结构:', response.data)
        accountsData = [];
      }
      
      // 设置账号数据
      accounts.value = accountsData;
    } else {
      ElMessage.error(response.message || '获取账号列表失败')
      accounts.value = []
    }
  } catch (error) {
    console.error('获取账号列表失败:', error)
    ElMessage.error('获取账号列表失败')
    accounts.value = []
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleSelectionChange = (selection) => {
  selectedAccounts.value = selection
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const showAddDialog = () => {
  accountDialog.visible = true
  accountDialog.isEdit = false
  accountDialog.form = {
    account: '',
    alias: '',
    account_type: 'wechat'
  }
}

const editAccount = (account) => {
  accountDialog.visible = true
  accountDialog.isEdit = true
  accountDialog.form = {
    account: account.account,
    alias: account.alias,
    account_type: account.account_type
  }
  accountDialog.currentId = account.id
}

const submitAccount = async () => {
  if (!accountFormRef.value) return
  
  try {
    await accountFormRef.value.validate()
    
    accountDialog.loading = true
    
    let response
    if (accountDialog.isEdit) {
      response = await accountAPI.updateAccount(accountDialog.currentId, accountDialog.form)
    } else {
      response = await accountAPI.createAccount(accountDialog.form)
    }
    
    if (response.success) {
      ElMessage.success(accountDialog.isEdit ? '更新账号成功' : '添加账号成功')
      accountDialog.visible = false
      await loadAccounts()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('操作失败')
    }
  } finally {
    accountDialog.loading = false
  }
}

const deleteAccount = async (account) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除账号 "${account.account}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await accountAPI.deleteAccount(account.id)
    if (response.success) {
      ElMessage.success('删除账号成功')
      await loadAccounts()
    } else {
      ElMessage.error(response.message || '删除账号失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除账号失败')
    }
  }
}

const getAccountTypeLabel = (type) => {
  const labels = {
    wechat: '微信',
    xiaohongshu: '小红书',
    douyin: '抖音',
    kuaishou: '快手',
    whatsapp: 'WhatsApp'
  }
  return labels[type] || type
}

const getAccountTypeColor = (type) => {
  const colors = {
    wechat: 'success',
    xiaohongshu: 'danger',
    douyin: 'warning',
    kuaishou: 'info',
    whatsapp: 'primary'
  }
  return colors[type] || 'default'
}

const formatTime = (timeStr) => {
  if (!timeStr) return '-'
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadAccounts()
})
</script>

<style scoped>
.account-page {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.page-description {
  color: #666;
  margin: 0;
  font-size: 14px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-icon.account-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stat-icon.wechat-icon {
  background: linear-gradient(135deg, #67C23A 0%, #85ce61 100%);
  color: white;
}

.stat-icon.other-icon {
  background: linear-gradient(135deg, #E6A23C 0%, #f0a020 100%);
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.account-list-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #2c3e50;
}

.header-right {
  display: flex;
  gap: 12px;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.account-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.account-name {
  font-weight: 500;
  color: #2c3e50;
}

.no-alias {
  color: #c0c4cc;
  font-style: italic;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-right {
    flex-direction: column;
  }
}
</style>